package com.jhl.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jhl.seckill.entity.Order;
import com.jhl.seckill.entity.SeckillGoods;
import com.jhl.seckill.entity.SeckillOrder;
import com.jhl.seckill.entity.User;
import com.jhl.seckill.mapper.OrderMQMapper;
import com.jhl.seckill.service.SeckillGoodsMQService;
import com.jhl.seckill.service.SeckillOrderMQService;
import com.jhl.seckill.service.SeckillService;
import com.jhl.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Primary
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    SeckillGoodsMQService seckillGoodsMQService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    OrderMQMapper orderMQMapper;

    @Autowired
    SeckillOrderMQService seckillOrderService;

    @Override
    public Order seckill(User user, GoodsVo goodsVo) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        SeckillGoods seckillGoods = seckillGoodsMQService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVo.getId()));

//        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
//                .setSql("stock_count = " + "stock_count-1")
//                .eq("goods_id", goodsVo.getId())
//                .gt("stock_count", 0));
        if (seckillGoods.getStockCount() < 1) {
//            redis中放置库存为0的key
            valueOperations.set("isStockEmpty:" + goodsVo.getId(), "0");
            return null;
        }
//        生成订单
        Order order = new Order();

        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate((new Date()));
        log.info("插入订单");
        orderMQMapper.insert(order);

        SeckillOrder SeckillOrder = new SeckillOrder();
        SeckillOrder.setUserId(user.getId());
        SeckillOrder.setOrderId(order.getId());
        SeckillOrder.setGoodsId(goodsVo.getId());
        seckillOrderService.save(SeckillOrder);
//        缓存秒杀订单
        log.info("缓存秒杀订单");
        redisTemplate.opsForValue().set("order:" + user.getId() + ":" + goodsVo.getId(), SeckillOrder);
        return order;
    }
}
